package hn.cch.microservice.service_provider_security.controller;

import hn.cch.microservice.service_provider_security.entity.User;
import hn.cch.microservice.service_provider_security.repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;

@RestController
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserRepository userRepository;

    @GetMapping(value = "/{id}")
    public User user(@PathVariable Long id){

        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof UserDetails){
            UserDetails userDetails = (UserDetails) principal;
            Collection<? extends GrantedAuthority> grantedAuthorities = userDetails.getAuthorities();
            for (GrantedAuthority grantedAuthority:grantedAuthorities) {
                logger.info("{}:{}", userDetails.getUsername(), grantedAuthority.getAuthority());
            }
        }else {
            logger.info("principal : " + principal.toString());
        }
        return userRepository.findOne(id);
    }

}
